package com.sgj.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.sgj.common.es.SkuEsModel;
import com.sgj.common.utils.R;
import com.sgj.gulimall.search.config.GulimallElasticSearchConfig;
import com.sgj.gulimall.search.constant.EsConstant;
import com.sgj.gulimall.search.feign.ProductFeignService;
import com.sgj.gulimall.search.service.MallSearchService;
import com.sgj.gulimall.search.vo.AttrResponseVo;
import com.sgj.gulimall.search.vo.SearchParam;
import com.sgj.gulimall.search.vo.SearchResult;
import com.sgj.gulimall.search.vo.SearchResult.CatalogVo;
import com.sgj.gulimall.search.vo.SearchResult.AttrVo;
import com.sgj.gulimall.search.vo.SearchResult.BrandVo;
import com.sgj.gulimall.search.vo.SearchResult.NavVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms.Bucket;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Author: Guoji Shen
 * @Date: 2021/7/21 14:34
 */
@Slf4j
@Service("mallSearchService")
public class MallSearchServiceImpl implements MallSearchService {

    public static final String ORDER = "asc";

    public static final String URL = "http://search.gulimall.com/list.html?";

    @Autowired
    private RestHighLevelClient client;

    @Autowired
    private ProductFeignService productFeignService;

    @Override
    public SearchResult search(SearchParam param) {

        SearchResult result = null;

        // 准备检索请求，构建出查询需要的DSL语句
        SearchRequest searchResult = buildSearchRequest(param);

        try {
            // 执行检索请求
            SearchResponse response = client.search(searchResult, GulimallElasticSearchConfig.COMMON_OPTIONS);

            // 分析响应数据并封装成 SearchResult
            result = buildSearchResult(response, param);

        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;
    }

    /**
     * 将响应数据封装成 SearchResult
     * @param response
     * @return
     */
    private SearchResult buildSearchResult(SearchResponse response, SearchParam param) {

        SearchHits hits = response.getHits();

        // 返回所有查询到的商品
        List<SkuEsModel> productList = new ArrayList<>();
        if (hits.getHits() != null && hits.getHits().length > 0) {
            for (SearchHit hit : hits.getHits()) {
                String sourceAsString = hit.getSourceAsString();
                SkuEsModel esModel = JSON.parseObject(sourceAsString, SkuEsModel.class);

                // 判断是否按关键字检索，若是就显示高亮，否则不显示
                if (StringUtils.isNotEmpty(param.getKeyword())) {
                    // 拿到高亮信息显示标题
                    String skuTitle = hit.getHighlightFields().get("skuTitle").getFragments()[0].string();
                    esModel.setSkuTitle(skuTitle);
                }

                productList.add(esModel);
            }
        }

        // 当前所有商品涉及到的所有属性信息
        List<AttrVo> attrVoList = new ArrayList<>();
        ParsedNested attrAgg = response.getAggregations().get("attr_agg");
        ParsedLongTerms attrIdAgg = attrAgg.getAggregations().get("attr_id_agg");
        for (Bucket bucket : attrIdAgg.getBuckets()) {
            // 属性id
            long attrId = bucket.getKeyAsNumber().longValue();
            // 属性名
            String attrName = ((ParsedStringTerms) bucket.getAggregations().get("attr_name_agg"))
                    .getBuckets().get(0).getKeyAsString();
            // 所有属性值
            List<String> attrValue = ((ParsedStringTerms) bucket.getAggregations().get("attr_value_agg")).getBuckets()
                    .stream()
                    .map(item -> item.getKeyAsString())
                    .collect(Collectors.toList());

            AttrVo attrVo = AttrVo.builder()
                    .attrId(attrId)
                    .attrName(attrName)
                    .attrValue(attrValue)
                    .build();
            attrVoList.add(attrVo);
        }

        // 当前所有商品涉及到的所有品牌信息
        List<BrandVo> brandVoList = new ArrayList<>();
        ParsedLongTerms brandAgg = response.getAggregations().get("brand_agg");
        for (Bucket bucket : brandAgg.getBuckets()) {
            // 品牌id
            long brandId = bucket.getKeyAsNumber().longValue();
            // 品牌名称
            String brandName = ((ParsedStringTerms) bucket.getAggregations().get("brand_name_agg"))
                    .getBuckets().get(0).getKeyAsString();
            // 品牌图片
            String brandImg = ((ParsedStringTerms) bucket.getAggregations().get("brand_img_agg"))
                    .getBuckets().get(0).getKeyAsString();

            BrandVo brandVo = BrandVo.builder()
                    .brandId(brandId)
                    .brandName(brandName)
                    .brandImg(brandImg)
                    .build();
            brandVoList.add(brandVo);
        }

        // 当前所有商品涉及到的所有分类信息
        List<CatalogVo> catalogVoList = new ArrayList<>();
        ParsedLongTerms catalogAgg = response.getAggregations().get("catalog_agg");
        for (Bucket bucket : catalogAgg.getBuckets()) {
            // 分类id
            long catalogId = Long.parseLong(bucket.getKeyAsString());
            // 分类名
            String catalogName = ((ParsedStringTerms) bucket.getAggregations().get("catalog_name_agg"))
                    .getBuckets().get(0).getKeyAsString();

            CatalogVo catalogVo = CatalogVo.builder()
                    .catalogId(catalogId)
                    .catalogName(catalogName)
                    .build();
            catalogVoList.add(catalogVo);
        }

        // 分页信息 - 总记录数
        long total = hits.getTotalHits().value;

        //5、分页信息-页码
        Integer pageNum = param.getPageNum();

        // 分页信息 - 总页码
        Integer totalPages = (int) (total + EsConstant.PRODUCT_PAGESIZE - 1) / EsConstant.PRODUCT_PAGESIZE;

        // 分页信息 - 导航页码
        List<Integer> pageNavs = new ArrayList<>();
        for (Integer i = 1; i <= totalPages; i++) {
            pageNavs.add(i);
        }

        // 导航 - 面包屑导航
        List<NavVo> navVoList = new ArrayList<>();
        List<Long> attrIds = new ArrayList<>();
        if (param.getAttrs() != null && param.getAttrs().size() > 0) {
            navVoList = param.getAttrs().stream().map(attr -> {
                // 分析每一个attrs传过来的参数值
                NavVo navVo = new NavVo();
                String[] s = attr.split("_");
                navVo.setNavValue(s[1]);
                R r = productFeignService.attrInfo(Long.parseLong(s[0]));
                attrIds.add(Long.parseLong(s[0]));
                if (r.getCode() == 0) {
                    AttrResponseVo data = r.getData("attr", new TypeReference<AttrResponseVo>() {
                    });
                    navVo.setNavName(data.getAttrName());
                } else {
                    navVo.setNavName(s[0]);
                }

                String replace = replaceQueryString(param, attr, "attrs");
                navVo.setLink(URL + replace);
                return navVo;
            }).collect(Collectors.toList());
        }

        // 品牌，分类
        if(!CollectionUtils.isEmpty(param.getBrandIds()) && param.getBrandIds().size() > 0) {
            List<NavVo> navs = navVoList;
            NavVo navVo = new NavVo();

            navVo.setNavName("品牌");
            R r = productFeignService.brandInfo(param.getBrandIds());
            if (r.getCode() == 0) {
                List<BrandVo> brand = r.getData("brand", new TypeReference<List<BrandVo>>() {
                });
                StringBuffer buffer = new StringBuffer();
                String replace = "";
                for (BrandVo brandVo : brand) {
                    buffer.append(brandVo.getBrandName() + ";");
                    replace = replaceQueryString(param, brandVo.getBrandId().toString(), "brandId");
                }
                navVo.setNavValue(buffer.toString());
                navVo.setLink(URL + replace);
            }
        }

        SearchResult result = SearchResult.builder()
                .products(productList)
                .catalogs(catalogVoList)
                .brands(brandVoList)
                .attrs(attrVoList)
                .pageNum(pageNum)
                .total(total)
                .totalPages(totalPages)
                .pageNavs(pageNavs)
                .navs(navVoList)
                .attrIds(attrIds)
                .build();

        log.info("[MallSearchServiceImpl][buildSearchResult] es返回数据为：{}", JSONObject.toJSONString(result));
        return result;
    }

    /**
     * 构建检索请求
     * @return
     */
    private SearchRequest buildSearchRequest(SearchParam param) {

        // 构建 DSL 语句
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        // 查询条件
        // 构建 bool - query
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        // must - 模糊匹配
        if (StringUtils.isNotEmpty(param.getKeyword())) {
            boolQuery.must(QueryBuilders.matchQuery("skuTitle", param.getKeyword()));
        }
        // filter - 按照三级分类id查询
        if (Objects.nonNull(param.getCatalog3Id())) {
            boolQuery.filter(QueryBuilders.termQuery("catalogId", param.getCatalog3Id()));
        }
        // filter - 按照品牌id查询
        if (!CollectionUtils.isEmpty(param.getBrandIds()) && param.getBrandIds().size() > 0) {
            boolQuery.filter(QueryBuilders.termsQuery("brandId", param.getBrandIds()));
        }
        // filter - 按照所有指定的属性进行查询
        if (!CollectionUtils.isEmpty(param.getAttrs()) && param.getAttrs().size() > 0) {

            // attrs=1_5寸:8寸&attrs=2_16G:8G
            for (String attrStr : param.getAttrs()) {
                BoolQueryBuilder nestedBoolQuery = QueryBuilders.boolQuery();
                // attr = 1_5寸:8寸
                String[] s = attrStr.split("_");
                // 检索的属性id
                String attrId = s[0];
                // 属性检索需要的值
                String[] attrValues = s[1].split(":");
                nestedBoolQuery.must(QueryBuilders.termQuery("attrs.attrId", attrId));
                nestedBoolQuery.must(QueryBuilders.termsQuery("attrs.attrValue", attrValues));
                // 每一个都必须生成一个单独的嵌入式(nested)查询
                NestedQueryBuilder nestedQuery = QueryBuilders.nestedQuery("attrs", nestedBoolQuery, ScoreMode.None);
                boolQuery.filter(nestedQuery);
            }
        }
        // filter - 按照是否有库存进行查询
        if (Objects.nonNull(param.getHasStock())) {
            boolQuery.filter(QueryBuilders.termQuery("hasStock", param.getHasStock() == 1));
        }
        // filter - 按照价格区间查询
        if (StringUtils.isNotEmpty(param.getSkuPrice())) {
            // skuPrice 的格式为 _500/500_      _在前则表示为小于等于，_在后则表示大于等于
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("skuPrice");
            // 将字符串格式进行拆分
            String[] price = param.getSkuPrice().split("_");
            // 若有两个值，则为一个区间
            if (price.length == 2) {
                rangeQuery.gte(price[0]).lte(price[1]);
            } else if (price.length == 1) {
                // 若只有一个值，则需要判断是大于还是小于
                if (param.getSkuPrice().startsWith("_")) {
                    rangeQuery.lte(price[0]);
                }
                if (param.getSkuPrice().endsWith("_")) {
                    rangeQuery.gte(price[0]);
                }
            }
            boolQuery.filter(rangeQuery);
        }
        // 封装所有查询条件
        sourceBuilder.query(boolQuery);

        // 排序
        if (StringUtils.isNotEmpty(param.getSort())) {
            String sort = param.getSort();
            // 排序参数格式: xxx_asc
            String[] s = sort.split("_");
            SortOrder order = ORDER.equalsIgnoreCase(s[1]) ? SortOrder.ASC : SortOrder.DESC;
            sourceBuilder.sort(s[0], order);
        }

        // 分页
        sourceBuilder.from((param.getPageNum() - 1) * EsConstant.PRODUCT_PAGESIZE);
        sourceBuilder.size(EsConstant.PRODUCT_PAGESIZE);

        // 高亮
        if (StringUtils.isNotEmpty(param.getKeyword())) {
            HighlightBuilder builder = new HighlightBuilder();
            builder.field("skuTitle");
            builder.preTags("<b style='color:red'>");
            builder.postTags("</b>");
            sourceBuilder.highlighter(builder);
        }

        // 聚合条件
        // 品牌聚合
        TermsAggregationBuilder brandAgg = AggregationBuilders.terms("brand_agg").field("brandId").size(50);
        // 品牌聚合的子聚合
        brandAgg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(1));
        brandAgg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1));
        sourceBuilder.aggregation(brandAgg);

        // 分类聚合
        TermsAggregationBuilder catalogAgg = AggregationBuilders.terms("catalog_agg");
        catalogAgg.field("catalogId").size(20);
        catalogAgg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(1));
        sourceBuilder.aggregation(catalogAgg);

        // 属性聚合
        NestedAggregationBuilder attrAgg = AggregationBuilders.nested("attr_agg", "attrs");
        // 聚合出所有的属性id
        TermsAggregationBuilder attrIdAgg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId");
        // 聚合分析出属性id对应的属性名称和值
        attrIdAgg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1));
        attrIdAgg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(50));
        attrAgg.subAggregation(attrIdAgg);
        sourceBuilder.aggregation(attrAgg);

        log.info("构建的DSL语句：{}", sourceBuilder);

        SearchRequest searchRequest = new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX}, sourceBuilder);

        return searchRequest;
    }

    /**
     * 替换路由地址
     * @param param
     * @param attr
     * @param key
     * @return
     */
    private String replaceQueryString(SearchParam param, String attr, String key) {
        // 取消了这个面包屑以后，我们要跳转到哪个地方，将请求的地址url里面的当前置空
        // 拿到所有的查询条件，去掉当前
        String encode = null;
        try {
            encode = URLEncoder.encode(attr,"UTF-8");
            // 浏览器对空格的编码和Java不一样，差异化处理
            encode.replace("+","%20");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return param.getQueryString().replace("&" + key + "=" + encode, "");
    }
}